﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OPMS_V1.BOL;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Data;
using OPMS_V1.DOL;

namespace OPMS_V1.Public
{
    public partial class ConfirmAd : System.Web.UI.Page
    {
        Register objRegBOL = new Register();
        Advertisement advertise = new Advertisement();
        Crypto crypt = new Crypto();
        DataSet ds = new DataSet();

        //Use of LINQ (Contains the collection of Stored Procedures
        S_PDataContext dc = new S_PDataContext();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Area"].Equals("") && Session["PostCode"].Equals("") && Session["State"].Equals(""))
            {
                //If no session available then redirect to SelfService
                Session["statusPage"] = "Ad";
                Response.Redirect("~\\Public\\SelfService.aspx?Mode=Ad");
            }
            lblUsernameError.Visible = false;
            lblRegisterError.Visible = false;
            regexReqUsername.Enabled = false;
            regexReqEmail.Enabled = false;
            //regexReqPassword.Enabled = false;
            lblRequired.Visible = false;
            lblLoginError.Visible = false;
            lblEmailExists.Visible = false;
            pnlRegistration.Visible = false;
        }

        /// <summary>
        /// This function is used for Login (Accessing the Confirm Ad Page)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //Registration details parameters
            string recordsExists;
            string LandLordID;
            string randomLandLordID;
            Boolean successful = false;
            string accountName = txtAccountName.Text;
            string password = crypt.Encrypt(txtPassword.Text);
            string lastLogin = System.Convert.ToString(DateTime.Now);

            //If the user enters no data in the fields, show errors
            if (accountName.Trim() == "" || txtPassword.Text.Trim() == "")
            {
                lblLoginError.Visible = true;
            }
            else
            {
                //Trying to validate the user with the Username and encrypted Password stored on to the database
                int response = objRegBOL.ValidateUser(accountName, password);

                if (response == 0)
                {
                    //Maitaing the session for the user logon.
                    successful = true;
                    Session["user"] = accountName;
                }
                else
                {
                    successful = false;
                    lblLoginError.Visible = true;
                }

                if (successful == true)
                {
                    //Get the Landlords personal details
                    ds = advertise.Get_PDetails(accountName);
                    try
                    {
                        recordsExists = ds.Tables[0].Rows[0][0].ToString();
                    }
                    catch(Exception)
                    {
                        recordsExists = null;
                    }
                    try
                    {
                        if (recordsExists != null)
                        {
                            LandLordID = ds.Tables[0].Rows[0][0].ToString();
                            Session["LogLandLordID"] = LandLordID;
                            txtFirstName.Text = ds.Tables[0].Rows[0][2].ToString();
                            txtLastName.Text = ds.Tables[0].Rows[0][3].ToString();
                            string sex = ds.Tables[0].Rows[0][4].ToString();
                            if (sex == "Male")
                            {
                                rdbMale.Checked = true;
                            }
                            else { rdbFemale.Checked = true; }
                            txtDOB.Text = ds.Tables[0].Rows[0][5].ToString();
                            txtPhone.Text = ds.Tables[0].Rows[0][6].ToString();
                            txtStreetNum.Text = ds.Tables[0].Rows[0][8].ToString();
                            txtStreetName.Text = ds.Tables[0].Rows[0][9].ToString();
                            txtPostCode.Text = ds.Tables[0].Rows[0][11].ToString();
                            txtArea.Text = ds.Tables[0].Rows[0][12].ToString();
                            string state = ds.Tables[0].Rows[0][13].ToString();
                            ddlState.SelectedValue = state;

                            btnConfirm.Visible = false;
                        }
                        else
                        {
                            if (Session["landlordID"].ToString() == "")
                            {
                                do
                                {
                                    //Generating the Random Task ID which is not present in Database
                                    randomLandLordID = advertise.RandomLandLordID();
                                } while (advertise.checkLandLordID(randomLandLordID));
                                Session["LogLandLordID"] = "owner" + randomLandLordID;
                            }
                            else
                            {
                                Session["LogLandLordID"] = Session["landlordID"].ToString();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        string s= null;
                    }
                    lblOR.Visible = false;
                    pnlLogin.Visible = false;
                    pnlRegistration.Visible = true;
                    pnlLoginDetails.Visible = false;
                    pnlRegisterTBD.Visible = false;
                    pnlExists.Style.Add("top", "50px");
                    chkTerms.Style.Add("top", "520px");
                    btnConfirmLogin.Style.Add("top", "520px");
                    lblRegisterError.Style.Add("top", "530px");
                }
            }
        }

        /// <summary>
        /// This function is used for Hideing the Panels, error messages
        /// </summary>
        /// <returns></returns>
        public Boolean Hide()
        {
            lblRegisterError.Visible = true;
            lblOR.Visible = false;
            lblRegisterError.Text = "Please accept the terms and conditions";
            pnlLogin.Visible = false;
            pnlRegistration.Visible = true;
            pnlLoginDetails.Visible = false;
            pnlRegisterTBD.Visible = false;

            return true;
        }

        /// <summary>
        /// This function is used for the Confirm Login Functionality.
        /// If the user looged on then he will be shown with the Confirm Login Button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnConfirmLogin_Click(object sender, EventArgs e)
        {
            //Personal Details
            Boolean transfer = false;
            string recordsExists;
            string LandLordID;
            Boolean condition = false;
            string fName = txtFirstName.Text;
            string lName = txtLastName.Text;
            string sex = "";
            if (rdbFemale.Checked == true)
            {
                sex = "Female";
            }
            else if (rdbMale.Checked == true)
            {
                sex = "Male";
            }

            string dob = txtDOB.Text;
            string phone = txtPhone.Text;
            string streetnum = txtStreetNum.Text;
            string streetName = txtStreetName.Text;
            string postCode = txtPostCode.Text;
            string area = txtArea.Text;
            string state = ddlState.SelectedValue;

            if (fName.Trim() == "" || lName.Trim() == "" || phone.Trim() == "" || streetnum.Trim() == "" || streetName.Trim() == "" || postCode.Trim() == "" || area.Trim() == ""||dob.Trim()=="")
            {
                lblRequired.Visible = true;
                pnlRegistration.Visible = true;
                condition = false;
            }
            else
            {
                string accountName=Session["user"].ToString();
                condition = true;
                if (condition == true)
                {
                    ds = advertise.Get_PDetails(accountName);
                    try
                    {
                        recordsExists = ds.Tables[0].Rows[0][0].ToString();
                    }
                    catch(Exception)
                    {
                        recordsExists = null;
                    }
                    try
                    {
                        if (recordsExists != null)
                        {
                            //Update the table
                            LandLordID = ds.Tables[0].Rows[0][0].ToString();
                            //ds = advertise.UpdatePDetails(fName, lName, sex, dob, phone, streetnum, streetName, postCode, area, state, LandLordID);

                            Session["recordExists"] = "true";
                            //Use of DataContext LINQ, to Update the table with the existing records.
                            dc.Update_LandLord_Details(@fName, @lName, @sex, @dob, @phone, @streetnum, @streetName, @postCode, @area, @state, @LandLordID);
                            //Go to different Page to show the preview

                            transfer = true;
                        }
                        else
                        {
                            string randomLandLordID = Session["LogLandLordID"].ToString();
                            string propID = Session["propertyID"].ToString();

                            Session["recordExists"] = "false";
                            //Store the values in session (Landlord's personal details)
                            Session["LogLandLordID"] = randomLandLordID;
                            Session["LFname"] = fName;
                            Session["LLname"] = lName;
                            Session["Lsex"] = sex;
                            Session["LDOB"] = dob;
                            Session["LPhone"] = phone;
                            Session["LStreetNum"] = streetnum;
                            Session["LStreetName"] = streetName;
                            Session["LPostCode"] = postCode;
                            Session["LArea"] = area;
                            Session["LState"] = state;
                            Session["propertyID"] = propID;
                            //Go to different Page to show the preview
                            transfer = true;
                        }
                    }
                    catch (Exception se)
                    {
                        string s = se.Message;
                    }
                    if (transfer == true)
                    {
                        if (chkTerms.Checked == true)
                        {
                            Response.Redirect("~//ManageAds//PreviewAd.aspx");
                        }
                        else
                        {
                            Hide();
                            pnlExists.Style.Add("top", "50px");
                            chkTerms.Style.Add("top", "520px");
                            btnConfirmLogin.Style.Add("top", "520px");
                            lblRegisterError.Style.Add("top", "520px");
                            btnConfirm.Visible = false;
                        }
                    }
                }
            }
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            string randomLandLordID;
            pnlContactDetails.Enabled = true;
            //Registration details parameters
            Boolean userexist = false;
            Boolean emailexist = false;
            Boolean successful = false;
            string accountName = txtRegAccountName.Text;
            string email = txtRegEmail.Text;
            string password = crypt.Encrypt(txtRegPassword.Text);
            string accountStatus = "Enabled";
            string accountType = "User";
            string IdentificationId = "IDN001";
            string lastLogin = System.Convert.ToString(DateTime.Now);

            //Personal Details
            string fName = txtFirstName.Text;
            string lName = txtLastName.Text;
            string sex="";
            if (rdbFemale.Checked == true)
            {
                sex = "Female";
            }
            else if (rdbMale.Checked == true)
            {
                sex = "Male";
            }
            
            string dob = txtDOB.Text;
            string phone = txtPhone.Text;
            string streetnum = txtStreetNum.Text;
            string streetName = txtStreetName.Text;
            string postCode = txtPostCode.Text;
            string area = txtArea.Text;
            string state = ddlState.SelectedValue;

            if (accountName.Trim() == "" || txtRegPassword.Text.Trim() == "" || email.Trim() == "" || fName.Trim()==""||lName.Trim()==""||phone.Trim()==""||streetnum.Trim()==""||streetName.Trim()==""||postCode.Trim()==""||area.Trim()==""||dob.Trim()=="")
            {
                lblRequired.Visible = true;
                pnlRegistration.Visible = true;
            }
            else
            {
                regexReqUsername.Enabled = false;
                regexReqEmail.Enabled = false;

                //This is used for getting all the usernames that exists.
                List<String> username = new List<string>();
                username = objRegBOL.getUsernames();

                //This is used for getting all the emailAddress that exists.
                List<String> emailaddress = new List<string>();
                emailaddress = objRegBOL.getEmailAddress();

                //If the Username matches then the username exists (TRY SOME ANOTHER USERNAME)
                foreach (string s in username)
                {
                    if (s.Equals(accountName))
                    {
                        userexist = true;
                    }
                }

                //If the email matches then the username exists (TRY SOME ANOTHER USERNAME)
                foreach (string s in emailaddress)
                {
                    if (s.Equals(email))
                    { emailexist = true; }
                }

                //If username not matches then register the user with the encrypted password stored on to the database
                if (userexist == false && emailexist == false)
                {
                    //Registering the user
                    try
                    {
                        //Registering the Details of the User (AccountName, email, password, accountStatus, accountType, IdentificationId, lastLogin
                        objRegBOL.RegisterUser(accountName, email, password, accountStatus, accountType, IdentificationId, lastLogin);
                        successful = true;
                        Session["user"] = accountName;
                    }
                    //If it fails to Register the User
                    catch (Exception)
                    {
                        lblRegisterError.Visible = true;
                        successful = false;
                        pnlRegistration.Visible = true;
                    }
                }
                //If the user exists then show that username exists.
                else
                {
                    //If the username exists then show the user exists message
                    if (userexist == true)
                    {
                        lblUsernameError.Visible = true;
                        successful = false;
                        pnlRegistration.Visible = true;
                    }
                    //If the email exists then show the email exists message
                    if (emailexist == true)
                    {
                        lblEmailExists.Visible = true;
                        successful = false;
                        pnlRegistration.Visible = true;
                    }
                }
                if (successful == true)
                {
                    if (Session["landlordID"].ToString() == "" || Session["landlordID"].ToString() == null)
                    {
                        do
                        {
                            //Generating the Random Task ID which is not present in Database
                            randomLandLordID = advertise.RandomLandLordID();
                        } while (advertise.checkLandLordID(randomLandLordID));
                        Session["LogLandLordID"] = "owner" + randomLandLordID;
                    }
                    else
                    {
                        Session["LogLandLordID"] = Session["landlordID"].ToString();
                    }
                    string propID = Session["propertyID"].ToString();

                    Session["recordExists"] = "false";
                    //Stroring session variables (Landlords personal details)
                    
                    Session["LFname"]=fName;
                    Session["LLname"] = lName;
                    Session["Lsex"] = sex;
                    Session["LDOB"] = dob;
                    Session["LPhone"] = phone;
                    Session["LStreetNum"] = streetnum;
                    Session["LStreetName"] = streetName;
                    Session["LPostCode"] = postCode;
                    Session["LArea"] = area;
                    Session["LState"] = state;
                    Session["LEmail"] = txtRegEmail.Text;
                    Session["propertyID"] = propID;
                    //Go to different Page to show the preview
                    Response.Redirect("~//ManageAds//PreviewAd.aspx");
                }
            }
        }

        protected void lnkForgot_Click(object sender, EventArgs e)
        {
            
            Response.Redirect("~/AccessControls/ForgottenPassword.aspx");
        }

        protected void lnkRegisterNow_Click(object sender, EventArgs e)
        {
            pnlLogin.Visible = false;
            lblOR.Visible = false;
            btnConfirmLogin.Visible = false;
            pnlRegisterTBD.Visible = false;
            pnlLoginDetails.Visible = true;
            pnlRegistration.Visible = true;
        }
    }
}
